/* 封装ajax函数
 * @param {string}option.method http连接的方式，包括POST和GET两种方式，默认使用GET
 * @param {string}option.url 发送请求的url
 * @param {boolean}option.async 是否为异步请求，true为异步的，false为同步的
 * @param {object}option.data 发送的参数，格式为对象类型
 * @param {function}option.success ajax发送并接收成功调用的回调函数
 */
function ajax(option) {
    option = option || {};

    var method = option.method || 'GET';
    method = method.toUpperCase() || 'GET';
    var url = option.url || '';
    var async = option.async || true;
    var data = option.data || null;
    var success = option.success || function () {
        };
    var xmlHttp = null;
    if (XMLHttpRequest) {
        xmlHttp = new XMLHttpRequest();
    }
    else {
        xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
    }
    var params = [];
    for (var key in data) {
        params.push(key + '=' + data[key]);
    }
    var dataStr = params.join('&');
    if (method === 'POST') {
        xmlHttp.open(method, url, async);
        xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');
        xmlHttp.send(dataStr);
    }
    else {
        xmlHttp.open(method, url + '?' + dataStr, async);
        xmlHttp.send(null);
    }
    xmlHttp.onreadystatechange = function () {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
            success(xmlHttp.responseText);
        }
    };
}
/* 表单验证 + ajax处理函数
 * @param selector : 通过ID或者class选择器获取的form表单对象，例如$('#myForm')
 * @param ajaxOption: 异步交互的设置项对象，包含method，url，data，success，error，async，所有设置项均有默认操作
 * @param msgCallback: 验证消息提示回调，默认调用light7的toast弹窗
 */
var checkform = function (selector, ajaxOption, confirmCallback, msgCallback) {
    var options = {
        success: function (result) {
            //检验重复提交
            if ($("button[type='submit']").hasClass('disabled') || $("input[type='submit']").hasClass('disabled')) {
                $('.cxvalidation_tip').html('请勿重复提交').addClass('show');
                return;
            }
            //验证成功禁用提交
            $("button[type='submit']").addClass('disabled').attr('disabled', 'true');
            $("input[type='submit']").addClass('disabled').attr('disabled', 'true');
            var method = ajaxOption.method || 'GET';
            method = method.toUpperCase() || 'GET';
            var url = ajaxOption.url || '';
            var async = ajaxOption.async || true;
            var data = ajaxOption.data || null;
            var dataType = ajaxOption.dataType || 'json';
            var confirm = ajaxOption.confirm || false;
            var confirm_title = ajaxOption.confirm_title || '';
            var confirm_content = ajaxOption.confirm_content || '是否提交当前表单 ？';
            var dataStr = '';
            if (data) {
                var params = [];
                for (var key in data) {
                    params.push(key + '=' + data[key]);
                }
                dataStr = params.join('&');
            }
            var paramData = selector.serialize();
            if (dataStr != '' && dataStr != undefined) {
                paramData += '&' + dataStr;
            }
            var dealAjax = function (status) {
                if (status) {
                    $.ajax({
                        type: method,
                        url: url,
                        data: paramData,
                        dataType: dataType,
                        async: async,
                        success: function (res) {
                            var ajaxres = res;
                            if (typeof(res) != 'object') {
                                ajaxres = JSON.parse(res);
                            }
                            if (ajaxres.status == 1) {
                                if (ajaxres.msg != '' && ajaxres.msg != undefined) {
                                    $('.cxvalidation_tip').css('background-color', 'rgb(64,196,2)');
                                    $('.cxvalidation_tip').html(ajaxres.msg).addClass('show');
                                }
                                if (ajaxOption.success && typeof(ajaxOption.success) == 'function') {
                                    if (ajaxres.msg != '' && ajaxres.msg != undefined) {
                                        setTimeout(function () {
                                            ajaxOption.success(ajaxres);
                                        }, 2000);
                                    } else {
                                        ajaxOption.success(ajaxres);
                                    }
                                }
                            } else {
                                var msg = '';
                                if (ajaxres.msg != '' && ajaxres.msg != undefined) {
                                    msg = ajaxres.msg;
                                } else {
                                    msg = '未知错误';
                                }
                                $('.cxvalidation_tip').html(msg).addClass('show');
                                if (ajaxOption.error && typeof(ajaxOption.error) == 'function') {
                                    if (ajaxres.msg != '' && ajaxres.msg != undefined) {
                                        setTimeout(function () {
                                            ajaxOption.error(ajaxres);
                                        }, 3000);
                                    } else {
                                        ajaxOption.error(ajaxres);
                                    }
                                }
                            }
                            var closeTipWait = setTimeout(function () {
                                $('.cxvalidation_tip').removeClass('show');
                                //请求成功开启提交
                                $("button[type='submit']").removeClass('disabled').removeAttr('disabled');
                                $("input[type='submit']").removeClass('disabled').removeAttr('disabled');
                            }, 3000);
                        },
                        error: function () {
                            $('.cxvalidation_tip').html('请求失败').addClass('show');
                            var closeTipWait = setTimeout(function () {
                                $('.cxvalidation_tip').removeClass('show');
                                //请求成功开启提交
                                $("button[type='submit']").removeClass('disabled').removeAttr('disabled');
                                $("input[type='submit']").removeClass('disabled').removeAttr('disabled');
                            }, 3000);
                        }
                    });
                }
            }
            if (confirm) {
                var confirmFlag = true;
                var new_confirm_content = confirm_content;
                if (confirm_content instanceof Array) {
                    new_confirm_content = eval(confirm_content[0])();
                }
                $.modal.prototype.defaults.modalCloseByOutside = false;
                $.confirm(new_confirm_content, confirm_title, function () {
                    if (confirmFlag) {
                        dealAjax(true);
                    }
                    confirmFlag = false;
                }, function () {
                    $('.cxvalidation_tip').removeClass('show');
                    //请求成功开启提交
                    $("button[type='submit']").removeClass('disabled').removeAttr('disabled');
                    $("input[type='submit']").removeClass('disabled').removeAttr('disabled');
                });
            } else {
                dealAjax(true);
            }
        },
    };
    if (msgCallback != '' && msgCallback != undefined && typeof(msgCallback) == 'function') {
        options['error'] = msgCallback;
    }
    $.cxValidation.attach(selector, options);
}
//get方法
function getData(url, data, success, error) {
    if (url == '' || url == undefined) {
        return;
    }
    var paramData = '';
    if (data) {
        var params = [];
        for (var key in data) {
            params.push(key + '=' + data[key]);
        }
        paramData = params.join('&');
    }
    $.ajax({
        type: 'GET',
        url: url,
        data: paramData,
        success: function (res) {
            var ajaxres = res;
            if (typeof(res) != 'object') {
                ajaxres = JSON.parse(res);
            }
            if (ajaxres.msg != '' && ajaxres.msg != undefined) {
                $.toast(ajaxres.msg);
                if (ajaxres.msg == '未授权访问' || ajaxres.msg == '当前账号已被禁用') {
                    setTimeout(function(){
                        deleteCache(login_key);
                        locationReplace('login.html');
                        return;
                    },2000);
                }

            }
            if (ajaxres.status == 1) {
                if (success && typeof(success) == 'function') {
                    success(ajaxres);
                }
            } else {
                if (error && typeof(error) == 'function') {
                    error(ajaxres);
                }
            }
        },
        error: function () {
            $.toast('请求失败');
        }
    });
}
//post方法
function postData(url, data, success, error) {
    if (url == '' || url == undefined) {
        return;
    }
    $.ajax({
        type: 'POST',
        url: url,
        data: data,
        success: function (res) {
            var ajaxres = res;
            if (typeof(res) != 'object') {
                ajaxres = JSON.parse(res);
            }
            if (ajaxres.msg != '' && ajaxres.msg != undefined) {
                $.toast(ajaxres.msg);
                if (ajaxres.msg == '未授权访问') {
                    setTimeout(function(){
                        deleteCache(login_key);
                        locationReplace('login.html');
                        return;
                    },2000);
                }
            }
            if (ajaxres.status == 1) {
                if (success && typeof(success) == 'function') {
                    success(ajaxres);
                }
            } else {
                if (error && typeof(error) == 'function') {
                    error(ajaxres);
                }
            }
        },
        error: function () {
            $.toast('请求失败');
        }
    });
}
//页面跳转
function redirect(url) {
    var flag = url.indexOf('?');
    if (flag > 0) {
        window.location.href = url + '&_='+ timestamp;
        return;
    }
    window.location.href = url + '?_='+ timestamp;
}

//设置缓存
function setCache(key, data) {
    if (!window.localStorage) {
        $.alert('浏览器不支持localstorage');
    } else {
        var storage = window.localStorage;
        storage.setItem(key, JSON.stringify(data));
    }
}
//获取缓存
function getCache(key) {
    if (!window.localStorage) {
        $.alert('浏览器不支持localstorage');
    } else {
        var storage = window.localStorage;
        return JSON.parse(storage.getItem(key));
    }
}
//删除缓存
function deleteCache(key) {
    if (!window.localStorage) {
        $.alert('浏览器不支持localstorage');
    } else {
        var storage = window.localStorage;
        storage.removeItem(key);
    }
}
//检查登录状态，未登录跳转到登录页
function checkLogin() {
    var worker_info = getCache(login_key)
    if (worker_info == '' || worker_info == undefined) {
        redirect('login.html');
    }
}


//从地址里面拿参数
function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null)return unescape(r[2]);
    return null;
}

//获取地址栏参数//可以是中文参数
function getUrlParam(key) {
    // 获取参数
    var url = window.location.search;
    url = decodeURI(url);
    // 正则筛选地址栏
    var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)");
    // 匹配目标参数
    var result = url.substr(1).match(reg);
    //返回参数值
    return result ? decodeURIComponent(result[2]) : null;
}

//添加时间戳
var timestamp = new Date().getTime();

function isEmpty(obj) {
    if(obj == undefined || obj == null || obj == ''){
        return 1;
    }else {
        return 0;
    }
}

function locationReplace(url){
    var flag = url.indexOf('?');
    if(flag > 0) {
        url += '&_=' + timestamp
    } else {
        url += '?_=' + timestamp;
    }
    location.replace(url);
}

//仅适用于需要改变按钮文本的弹框（bottom必填）
$.alert_new = function (text, title , bottom,callbackOk) {
    if (typeof title === 'function') {
        callbackOk = arguments[1];
        title = undefined;
    }
    if(typeof  bottom === 'function') {
        bottom = defaults.modalButtonOk;
    }
    return $.modal({
        text: text || '',
        title: typeof title === 'undefined' ? defaults.modalTitle : title,
        buttons: [ {text: bottom, bold: true, onClick: callbackOk} ]
    });
};


//封装过期控制代码
function setCache_outTime(key, value) {
    if (!window.localStorage) {
        $.alert('浏览器不支持localstorage');
    } else {
        var curTime = new Date().getTime();
        localStorage.setItem(key, JSON.stringify({data: value, time: curTime}));
    }

}
function getCache_outTime(key, exp) {
    var data = localStorage.getItem(key) || '';
    if (data) {
        var dataObj = JSON.parse(data);
        var now_time = new Date().getTime();
        if (now_time / 1000 - dataObj.time / 1000 > exp) {
            console.log('信息已过期');
            return false;
        } else {
            var dataObjDatatoJson = dataObj.data;
            return dataObjDatatoJson;
        }
    }

}
